class Solution(object):
    def unhappyFriends(self, n, preferences, pairs):
        p = [set() for _ in range(n)]
        for u, v in pairs:
            for t in preferences[u]:
                if t != v:
                    p[u].add(t)
                else:
                    break
            for t in preferences[v]:
                if t != u:
                    p[v].add(t)
                else:
                    break
        ans = 0
        for i in range(n):
            for v in p[i]:
                if i in p[v]:
                    ans += 1
                    break
        return ans
